#!/usr/bin/python3
# -*- coding: utf-8 -*-
#TODO:
#1. Add favourite pictures, the favourite pics won't be deleted
#2. Make this app a service, run daily
#3. Other settings

import os.path
import shutil
import glob
import sys
import urllib.request
import re

recyclepics = False
recyclepath = '' #Pictures out of date
outPath = ''
maxPicCount = 10
urlpath = "http://cn.bing.com"

def getHtml(url):
	page = urllib.request.urlopen(url)
	html = page.read()
	return html.decode('UTF-8')

def getBKImageUrl(page, path):
	reg = r'g_img={url: "[^"]*'
	imgre = re.compile(reg)

	imglist = imgre.findall(page)
	for imgsrc in imglist:
		rsrc = imgsrc[imgsrc.find('"')+1:]
		opath = '{}/{}'.format(path, rsrc[rsrc.rfind('/')+1:])
		success = True
		try:
			try:
				print('Picture found: ', rsrc);
				print('Downloading...');
				urllib.request.urlretrieve(rsrc, opath)
				print('Download Success');
			except:
				rsrc = urlpath + '/' + imgsrc[imgsrc.find('"')+1:]
				print('Downloading failed.');
				print('Try download url ', rsrc)
				urllib.request.urlretrieve(rsrc, opath);
				print('Download Success');
		except:
			print('Download failed');
			success = False
		if success:
			print('Finish downloading, save picture to ', opath);

def GetTodaysBackground():
	bingpage = getHtml(urlpath)
	getBKImageUrl(bingpage, outPath)

def printimgs(imgs):
	print('NO.\t Path')
	idx = 1
	for img in imgs:
		print(idx,'\t',img[0])
		idx = idx + 1

def GetAllPicsInTimeOrder():
	imgfiles = glob.glob('{}/*.jpg'.format(outPath))
	return sorted([(name, os.path.getmtime(name)) for name in imgfiles],
               key = lambda st:st[1])

def DeletePicsOutofDate():
	if maxPicCount > 0:
		imgs = GetAllPicsInTimeOrder()
		idx = 0
		while len(imgs) - idx > maxPicCount:
			if recyclepics and os.path.isdir(recyclepath):
				imgpath = imgs[idx][0]
				slash = max(imgpath.rfind('\\'), imgpath.rfind('/'))
				outpath = recyclepath + '/' + imgpath[slash + 1:]
				print('Move ', imgs[idx][0], outpath)
				shutil.move(imgs[idx][0], outpath)
			else:
				print("Remove ", imgs[idx][0])
				os.remove(imgs[idx][0])
			idx = idx + 1

def ShowSettings():
	print('Picture path: ', outPath)
	print('Max pictures cached: ', maxPicCount)
	print('Recycle pictures out of date: ', recyclepics)
	print('Recycle path: ', recyclepath)

def Help():
	print("-----bwapp help------")
	print("u：Fetch total's picture and delete pictures out of date")
	print("l：List all pictures cached")
	print('s: Perference Settings')
	print('sm: Set max cached pictures')
	print('sp: Set cached picture path')
	print('sr: Set recycle or delete pictures out of date')
	print('srp: Set recycle path')
	print('dl: Download html file')
	print("h：Help")
	print('q: Exit')

def GetCurPath():
	path = sys.path[0]
	if os.path.isdir(path):
		return path
	elif os.path.isfile(path):
		return os.path.dirname(path)
	return outPath

def GetPerferencePathname():
	return os.path.join(GetCurPath(), 'settings')

def SetOutputPath(path):
	global outPath
	if os.path.isdir(path):
		print('Set cached path to ', path)
		outPath = path
	else:
		print('Path', path, 'not exist')

def SetMaxCachedPictures(count):
	global maxPicCount
	if count >= 0:
		print('Set max cached pictures to ', count)
		maxPicCount = count
def SetRecyclePictures(brecycle):
	global recyclepics
	recyclepics = brecycle
	print('Set recycle pictures ', brecycle)

def SetRecyclePath(path):
	path.strip()
	global recyclepath
	if os.path.exists(path):
		print('Set recycle path to ', path)
		recyclepath = path
	else:
		if path != '' and input('Recycle path is not exists. Create (Y/N)? \n-->').lower() == 'y':
			os.mkdir(path)
			if os.path.isdir(path):
				recyclepath = path
				print('Set recycle path to ', path)


def LoadPerference():
	spath = GetPerferencePathname()
	try:
		of = open(spath, 'r')
		print('Load preference from ', spath)
		try:
			l = of.readline()
			while len(l):
				if l.find('=') > 0:
					ls = l.split('=')
					if ls[0].startswith('Cached Path'):
						SetOutputPath(ls[1][:-1])
					elif ls[0].startswith('Max Count'):
						try:
							num = int(ls[1])
							SetMaxCachedPictures(num)
						except:
							pass
					elif ls[0].startswith('Recycle Pictures'):
						bres = False
						strres = ls[1][:-1].lower()
						if strres.startswith('yes') or strres.startswith('true'):
							bres = True
						SetRecyclePictures(bres)
					elif ls[0].startswith('Recycle Path'):
						SetRecyclePath(ls[1][:-1])
				l = of.readline()
		finally:
			of.close()
	except FileNotFoundError:
		print('Open perference file failed')

def SavePererence():
	spath = GetPerferencePathname()
	print('Save perference to ', spath)
	of = open(spath, 'w+')
	try:
		of.write('Cached Path={}\n'.format(outPath))
		of.write('Max Count={}\n'.format(maxPicCount))
		of.write('Recycle Pictures={}\n'.format(recyclepics))
		of.write('Recycle Path={}\n'.format(recyclepath))
	finally:
		of.close()

def CheckCachePath():
	global outPath
	sp = outPath
	while not os.path.isdir(sp):
		sp = input('Please set a picture cache path: ')
		if os.path.exists(sp):
			c = input('Path {} already exists. The pictures in this path may be destoryed. Continue? (Y/N)'.format(sp))
			if c == 'Y' or c == 'y':
				break
		elif os.path.isdir(sp):
			c = input('Path {} is not exist.'.format(sp))
			if c == 'Y' or c == 'y':
				os.mkdir(sp)
				break
	outPath = sp
def DownLoadFullHtml():
	page = urllib.request.urlopen(urlpath)
	html = page.read()
	outpath = input('Output file path: ')
	try:
		of = open(outpath, 'wb')
	except:
		print('Save html file failed.')
		return

	try:
		of.write(html)
		print('Save html to ', outpath, ' success.')
	finally:
		of.close()

def MainLoop():
	LoadPerference()
	print('Welcome to bwapp, input h for help')
	CheckCachePath()
	while True:
		cmd = input('\n-->')
		if cmd.lower() == 'u':
			GetTodaysBackground();
			DeletePicsOutofDate();
		elif cmd.lower() == 'h':
			Help()
		elif cmd.lower() == 'q':
			break
		elif cmd.lower() == 'l':
			printimgs(GetAllPicsInTimeOrder())
		elif cmd.lower() == 's':
			ShowSettings()
		elif cmd.lower() == 'sm':
			try:
				SetMaxCachedPictures(int(input('Input a number: \n-->')))
			except:
				print('input error.')
		elif cmd.lower() == 'sp':
			SetMaxCachedPictures(input('Input a valid path:\n-->'))
		elif cmd.lower() == 'sr':
			SetRecyclePictures(input('Recycle pictures (Y/N): ').lower() == 'y')
		elif cmd.lower() == 'srp':
			SetRecyclePath(input('Input a valid path:\n-->'))
		elif cmd.lower() == 'dl':
			DownLoadFullHtml()
		else:
			print('Input error, input h for help')
	SavePererence()



if __name__ == '__main__':
	argc = len(sys.argv)
	if argc == 2:
		if sys.argv[1] == '-u':
			LoadPerference()
			CheckCachePath()
			GetTodaysBackground();
			DeletePicsOutofDate();
	else:
		MainLoop()
